package tv_megazineplus
import org.codehaus.groovy.runtime.TimeCategory
import groovy.time.TimeDuration

class SendAlertJob {
    def timeout = 30000l // execute job once in 30 seconds
    def SendMailService
    def SendSmsService
        
    
    def execute() {
        
        def userNumber
        def email  
        def alerts
        def start, end, end2, rp
        TimeDuration td
        
            use(TimeCategory){
                alerts = Alert.findByHoraDisparaBetween(new Date(), new Date() + 5.minutes)
                }
            
            alerts.each{
                
                userNumber = it.user.phoneNumber
                email = it.user.email
                
                rp = it.program.prog_start
                td = TimeCategory.minus( rp, new Date())
                
                if(it.sent == 0){
                    //SMS
                    if(it.tipo == 'sms'){
                        start = System.currentTimeMillis()
                        sendSmsService.serviceMethod("TvMagP", userNumber, 
                        "O programa <" + it.program.getProgrammationName() + "> do canal <" + it.program.prog_channel.getChannel2() + 
                        "> começa daqui a " + td + "\n <<" + it.personalMessage + ">>")
                    
                        it.sent=1
                        it.save()
                        end = System.currentTimeMillis()
                        end2 = new Date()
                        new Statistic(servico: Servicos.findByNameLike('Serviço de Alertas - SMS'), totalTime: end-start, date: end2).save()
                    //EMAIL    
                    }else{
                    start = System.currentTimeMillis()  
                        SendMailService.serviceMethod(email, "Alerta TvMagazinePlus", "O programa <" + it.program.getProgrammationName() + "> do canal <" + it.program.prog_channel.getChannel2() + 
                        "> começa daqui a " + td + "\n <<" + it.personalMessage + ">>")
                    
                        it.sent=1
                        it.save()
                        end = System.currentTimeMillis()
                        end2 = new Date()
                        new Statistic(servico: Servicos.findByNameLike('Serviço de Alertas - EMAIL'), totalTime: end-start, date: end2).save()
                        }
                    
                   
                }else{
                    //doNothing()
                }
            }
                             
        
}
}
